/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: mirac
 * Date: 2025-08-24
 * Time: 22:52
 */
public class Solution {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }
    }
    private int preIndex;
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return func(preorder,inorder,0,inorder.length - 1);
    }

    private TreeNode func(int[] preorder,int[] inorder,int inbegin,int inend) {
        if(inbegin > inend) {
            return null;
        }

        TreeNode root = new TreeNode(preorder[preIndex]);
        int rootIndex = findIndex(inorder,inbegin,inend,preorder[preIndex]);
        preIndex++;
        root.left = func(preorder,inorder,inbegin,rootIndex - 1);
        root.right = func(preorder,inorder,rootIndex + 1,inend);

        return root;

    }
    private int findIndex(int[] inorder,int inbegin,int inend,int val) {
        for(int i = inbegin; i <= inend; i++) {
            if(inorder[i] == val){
                return i;
            }
        }
        return -1;
    }
}
